//
//  Color+Extension.swift
//  TheWatermark
//
//  Created by 沙睿 on 2021/6/6.
//

import Foundation
import SwiftUI

extension Color {
    /// 通过16进制字符串获取颜色
    ///
    /// - Parameters:
    ///   - hexStr: 16进制字符串('0Xffffff', '0Xffffff', '#ffffff', 'ffffff')
    ///   - alpha: 透明度
    /// - Returns: UIColor
    static func sr_color(hex hexStr: String, alpha: Double = 1.0) -> Color {
        var cstr = hexStr.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        if cstr.count < 6 {
            return Color.clear
        }
        if cstr.hasPrefix("0X") {
            cstr = cstr.sr_subString(from: 2)
        }else if cstr.hasPrefix("0x") {
            cstr = cstr.sr_subString(from: 2)
        }else if cstr.hasPrefix("#") {
            cstr = cstr.sr_subString(from: 1)
        }
        if cstr.count != 6 {
            return Color.clear
        }
        var range = NSRange.init()
        range.location = 0
        range.length = 2
        //r
        let rStr = cstr.sr_subString(range)
        //g
        range.location = 2
        let gStr = cstr.sr_subString(range)
        //b
        range.location = 4
        let bStr = cstr.sr_subString(range)
        
        var r: UInt64 = 0x0;
        var g: UInt64 = 0x0;
        var b: UInt64 = 0x0;
        Scanner.init(string: rStr).scanHexInt64(&r)
        Scanner.init(string: gStr).scanHexInt64(&g)
        Scanner.init(string: bStr).scanHexInt64(&b)
        return Color.init(red: Double(r)/255.0, green: Double(g)/255.0, blue: Double(b)/255.0, opacity: alpha);
    }
}
